package com.youwe1.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youwe1.wiki.domain.Ebook;
import com.youwe1.wiki.domain.EbookExample;
import com.youwe1.wiki.mapper.EbookMapper;
import com.youwe1.wiki.req.EbookQueryReq;
import com.youwe1.wiki.req.EbookSaveReq;
import com.youwe1.wiki.resp.EbookQueryResp;
import com.youwe1.wiki.resp.PageResp;
import com.youwe1.wiki.util.CopyUtil;
import com.youwe1.wiki.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {

    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        // where 条件 判断name是不是空
        if (!ObjectUtils.isEmpty(req.getName())) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        // where 条件 判断categoryId2
        if (!ObjectUtils.isEmpty(req.getCategoryId2())) {
            criteria.andCategory2IdEqualTo(req.getCategoryId2());
        }

        List<Ebook> ebookList;
        // 第一页从1开始。而且只会对最近的一条查询方法有效!!!!!
        PageHelper.startPage(req.getPage(), req.getSize());
        // 查询方法
        ebookList = ebookMapper.selectByExample(ebookExample);
        if (req.getPage() > 1 && ebookList.isEmpty()) {
            // 如果当前页没有数据，页码就减一再次查询
            PageHelper.startPage(req.getPage() - 1, req.getSize());
            ebookList = ebookMapper.selectByExample(ebookExample);
        }
        // 将查询出来的数据处理，去掉无用数据，只返回EbookResp里定义的属性
        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        // 生成pageInfo用于获取total
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        // 分页实例
        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());
        pageResp.setPage(req.getPage());
        pageResp.setSize(req.getSize());
        pageResp.setList(list);
        return pageResp;
    }

    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());

            // 测试！！！！！！！
            ebook.setDocCount(0);
            ebook.setViewCount(0);
            ebook.setVoteCount(0);

            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
